package net.onewfour.control;


import net.onewfour.dao.detail.DBUser;
import net.onewfour.utils.OneW4Utils;

import org.apache.commons.lang.StringUtils;

import com.jfinal.core.CMSController;
import com.jfinal.core.CMSHandlers;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.RenderFactory;

/**
 * 
 * @author Marc
 * @version 1.0
 */
public class BaseControl extends CMSController {
	
	private static final String ADMINFOLDER = "/admin/";
	
	private static final String _UserCookiesName = "1W4_SiteCookie";

	private static final RenderFactory renderFactory = RenderFactory.me();
	
	
	public static final boolean devMode = CMSHandlers.devMode;
	
	public static String THEME_FOLDER = "";
	
	public static final int _WEEKTIME = 60 * 60 * 60 ;
	
	public void Error500(){
		renderFactory.getErrorRender(500).setContext(getRequest(), getResponse());
	}
	
	@Override
	public void setAttrDefualt() {
		setAttr("adminurl", CMSHandlers.getAdminUrl());
	}
	
	public String getCookiesName(){
		return _UserCookiesName ;
	}
	
	public Record getUserFromCookies() {
		String str = getCookie(getCookiesName());
		if(validataNotNull(str)){
			return null ; 
		}
		String[] keys = str.split(",");
		if(keys.length !=2){
			return null ; 
		}
		Record cord= DBUser.instance().getUserByID(keys[1]);
		if(cord!=null && MD5(cord.getStr("username")+cord.getStr("userpwd")).equals(keys[0])){
			return cord ;
		}
		return null ; 
	}
	
	public void setCookies(Record cord) {
		setCookie(getCookiesName(), MD5(cord.getStr("username")+cord.getStr("userpwd"))+","+cord.getInt("id"), _WEEKTIME);
	}
	
	private String MD5(String string) {
		return OneW4Utils.MD5(string);
	}

	public void renderAdmin(String string) {
		render(ADMINFOLDER+string);
	}

	
	
	/* (non-Javadoc)
	 * @see com.jfinal.core.Controller#render(java.lang.String)
	 */
	@Override
	public void render(String view) {
		
		super.render(THEME_FOLDER+view);
	}

	/* (non-Javadoc)
	 * @see com.jfinal.core.Controller#render(java.lang.String, int)
	 */
	@Override
	public void render(String view, int status) {
		
		super.render(THEME_FOLDER+view, status);
	}

	/**
	 * 参数有一个为null "" "  "则为true 
	 * @user Marc
	 * @createtime 2014-8-11 下午04:21:19
	 * @param args
	 * @return
	 */
	public boolean validataNotNull(String...args){
		for (int i = 0; i < args.length; i++) {
			if(StringUtils.isBlank(args[i])){
				return true ; 
			}
		}
		return false ; 
	}
	
	
	
}
